package cn.wolfcode.luowowo.controller;


import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.Consts;
import cn.wolfcode.luowowo.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("region")
public class RegionController {


    @Autowired
    private IRegionService regionService;
    @Autowired
    private IDestinationService destinationService;


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") RegionQuery qo){

        //看前端页面共享个page
        // pageinfo :是mybatis插件,操作的是mysql数据库
        // Page  : 是spring-data 的组件,操作的是mongodb
        Page<Region> page =  regionService.query(qo);

        model.addAttribute("page",page);
        return "region/list";
    }

    // 添加按钮中目的地下拉框:查询所有目的地数据
    @RequestMapping("/listDests")
    @ResponseBody
    public Object listDests(){
        // 查询所有目的地数据(这里不用共享,因为前端发送的是ajax请求,要的是json格式的数据)
        return destinationService.listAll();
    }

    // 添加按钮中保存操作
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Region region){

        try {
            // 保存和编辑
            regionService.saveOrUpdate(region);
            return JsonResult.success();
        }catch (LogicException e){
            e.printStackTrace();
            throw new LogicException(JsonResult.MSG_ERROR);//系统异常
        }
    }

    // 页面目的地查看按钮:查询目的地
    @RequestMapping("/getDestByRegionId")
    @ResponseBody
    public Object getDestByRegionId(String rid){

        try {
            // 保存和编辑
            List<Destination> list =  destinationService.queryDestByRegionId(rid);
            return list;
        }catch (LogicException e){
            e.printStackTrace();
            throw new LogicException(JsonResult.MSG_ERROR);//系统异常
        }
    }

    // 后端页面设置热门按钮
    @RequestMapping("/changeHotValue")
    @ResponseBody
    public Object changeHotValue(int hot,String id){

        try {
            regionService.changeHotValue(hot,id);

            return JsonResult.success();
        }catch (LogicException e){
            e.printStackTrace();
            throw new LogicException(JsonResult.MSG_ERROR);//系统异常
        }
    }
}
